const SerialPort = require('serialport');
const Regex = require('@serialport/parser-regex')
const fs = require("fs");
const csv = require('csv-parser');

const portName = 'COM5'; //定义串口名1

const csvFile = 'am_tele_message_202110191314.csv';//报文数据文件

const originalTextField = 'original_text';//报文字段名称，CSV的标题行

const sendInterval=1000;//发报间隔，单位毫秒

const serialPort = new SerialPort( //设置串口属性
	portName, {
	  baudRate: 9600,  //波特率
	  dataBits: 8,    //数据位
	  parity: 'none',  //奇偶校验
	  stopBits: 1,  //停止位
	  flowControl: false ,
	  autoOpen:false //不自动打开
	}, false);

//过滤报文条件，返回true则发送该报
function doFilter(row){
	let bSend=true;
	bSend = row['msg_category']!=='NOTAM'&&row['msg_category']!=='METAR'&&row['msg_category']!=='SNOWTAM'&&row['msg_category']!=='TAF';
	return bSend;
}

const parser = serialPort.pipe(new Regex({regex:/(?:ZCZC|\u0001)\s*([\s\S]*?)\s*(?:NNNN|\u0003)/}))
parser.on('data',function(msg){
	const aftnSitaRegex = /(?:([A-Z]{3})(\d{3,4})(?:\s+(\d{6}))?\s+([A-Z]{2})\s+([A-Z]{8})\s+(\d{6})\s+([A-Z]{8})|([A-Z]{3})(\d{3,4})(?:\s+(\d{6}))?\s+([A-Z]{2})\s+(\w{7})\s*(?:\.\s*([A-Z]{2})\s*((?:\w{7}\s+)+))?\s+\.(\w{7})\s+(\d{6}))\s+([\s\S]*)/
	const groups = msg.match(aftnSitaRegex)
	
	if(groups&&groups[1]){
		const [,cid,csn,info,pri,addresses,time,ori,,,,,,,,,,text] = groups
		const aftnMsg = {cid,csn,info,pri,addresses,time,ori,text}
		console.log('AFTN Message:',aftnMsg)
	}else if(groups&&groups[8]){
		const [,,,,,,,,cid,csn,info,pri,addresses,priCopy,addressesCopy,ori,time,text] = groups
		const sitaMsg = {cid,csn,info,pri,addresses,priCopy,addressesCopy,time,ori,text}
		console.log('SITA Message:',sitaMsg)
	}else{
		console.log('Unknow message:',msg)
	}
})

serialPort.open(function(error){
	  if(error){
	    console.log("打开端口"+portName+"错误："+error);
	  }else{ 
	  	console.log("打开端口成功，正在监听数据中");
	  }
});

let datas=[]
fs.createReadStream(csvFile).pipe(csv()).on('data', (data) => {
        datas.push(data)
      }).on('end', () => {
						main()
      })

function sleep(ms) {
    return new Promise(resolve=>setTimeout(resolve, ms))
}
async function main() {
		console.log("do main()")
	  for(let row of datas){
			//过滤报文
	    if(doFilter(row)){
	  		console.log('---------------------------------------------------------------------------------')
	  		console.log(row[originalTextField])
	  		serialPort.write(row[originalTextField])        	  		
				await sleep(sendInterval)
	  	}
			/*
			//for bms
			 fs.writeFile('c:/temp/SITA/'+row['CSN']+'.RCV', row['ORIGINAL_TEXT'], function (error) {
			  if (error) {
			    console.log('faild',new Date())
			  } else {
			    console.log('success',new Date())
			  }
			})*/
	  }
		console.log("end main()")
}